package com.sjb.cp.utils;

import org.springframework.stereotype.Component;

import java.awt.*;

/**
 * @Author:sjb
 * @CreateTime:2025-02-10
 * @Description: 图片颜色相似度计算工具类
 * @Version：1.0
 */
@Component
public class ColorSimilarUtils {


    private ColorSimilarUtils(){

    }

    /**
     * 颜色计算相似度  欧几里得距离算法
     * @param color1
     * @param color2
     * @return
     */
    public static double calculateSimilarity(Color color1, Color color2){
        int r1 = color1.getRed();
        int g1 = color1.getGreen();
        int b1 = color1.getBlue();

        int r2 = color2.getRed();
        int g2 = color2.getGreen();
        int b2 = color2.getBlue();

        double distance = Math.sqrt(Math.pow(r2 - r1, 2) + Math.pow(g2 - g1, 2) + Math.pow(b2 - b1, 2));

        return 1 - distance / Math.sqrt(3 * Math.pow(255,2));
    }

    /**
     * 十六进制计算颜色相似度
     * @param color1
     * @param color2
     * @return
     */
    public static double calculateSimilarity(String color1, String color2){
        Color hexColor1 = Color.decode(color1);
        Color hexColor2 = Color.decode(color2);

        return ColorSimilarUtils.calculateSimilarity(hexColor1, hexColor2);
    }

    public static void main(String[] args) {
        Color color1 = Color.decode("0xFF0000");
        Color color2 = Color.decode("0xFE0101");

        double calculated = calculateSimilarity(color1, color2);
        System.out.println(calculated);

        double calculated1 = calculateSimilarity("0xFF0000", "0xFE0101");
        System.out.println("十六进制颜色" + calculated1);
    }

}
